/*
 * @ author madman 
 * @ use 后台用户列表
 */
const AdminModel = require('../../models/system/admin.model');
const Utils = require('../utils');
import md5 from 'md5';
class AdminUserController {
    // 添加
    async add(ctx) {
        const _body = ctx.request.body
        const _params = {
            username: _body.username,
            password: md5(_body.password),
            power: _body.power,
        }
        const result = await AdminModel.create(_params);
        if (result) {
            return ctx.success({ msg: '添加成功' });
        } else {
            return ctx.error({ msg: '添加失败' });
        }
    }
    // 更新
    async update(ctx) {
        const _body = ctx.request.body
        const _params = Utils._params(_body)
        if(_params.password){
            _params.password = md5(_body.password)
        } else {
            delete _params.password
        }
        _params.updataAt = new Date()
        const result = await AdminModel.update({ _id: _body._id }, { $set: _params });
        if (result) {
            return ctx.success({ msg: '更新成功' });
        } else {
            return ctx.error({ msg: '更新失败' });
        }
    }

    // 删除
    async delete(ctx) {
        const _id = ctx.query.id
        const result = await AdminModel.remove({ _id: _id });
        if (result) {
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }
    /*
     * 批量删除方法
     */
    async batchdelete(ctx, name) {
        const arrids = ctx.request.body.arrids
        let result = await AdminModel.remove({ _id: { $in: arrids } })
        if (result) {
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }

    // 获取带分页列表
    async list(ctx) {
        const options = {
            name: 'system/admin',
            type: 'pop',
            populate: 'power',
            sortType: 'sort',
            sortVal: '1'
        }
        let result = await Utils.getPageList(ctx, options)
        if (result) {
            return ctx.success({
                data: result,
                msg: '查询成功'
            });
        }
    }

}

export default new AdminUserController;